package com.toman.ui.work.choose;

import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.toman.Adpter.ItemListAdapter;
import com.toman.Interfaces.NewBaseUrl;
import com.toman.R;
import com.toman.Util.IntentUtils;
import com.toman.Util.KeybordS;
import com.toman.Util.ViewUtil;
import com.toman.toolbar.LoadingEmptyActivity;
import com.toman.widget.MyListView;
import com.toman.Util.ToastUtil;
import com.toman.bean.ItemListBean;
import com.toman.ui.work.base.HardwaveInfActivity;
import com.itheima.pulltorefreshlib.PullToRefreshBase;
import com.itheima.pulltorefreshlib.PullToRefreshScrollView;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.toman.widget.callback.ErrorCallback;
import com.toman.widget.callback.PostUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;

public class ChooseHardwaveListEmptyActivity extends LoadingEmptyActivity {

    @BindView(R.id.et_search)
    EditText etSearch;

    @BindView(R.id.mMangeNodata)
    TextView mMangeNodata;
    @BindView(R.id.lv)
    MyListView lv;
    @BindView(R.id.mPullToRefreshScrollView)
    PullToRefreshScrollView mPullToRefreshScrollView;
    ItemListAdapter adapter;
    List<ItemListBean> list = new ArrayList<ItemListBean>();
    int totalPage = 100;
    int page = 2;
    String id;
    @BindView(R.id.tv_select)
    TextView tvSelect;
    @BindView(R.id.fl_et)
    RelativeLayout flEt;
    private RelativeLayout rlIten1, rlItem2, rlBase;
    private LinearLayout llItem;
    private Button btnSearch;
    int type=1;
    MyListView lvItem;
    List<ItemListBean> listItem = new ArrayList<ItemListBean>();
    ItemListAdapter adapterItem;

    private ImageView imageCloseOne,imageCloseTwo,iv_back,iv_del1,iv_del2;
    private TextView tv_content1,tv_content2,tv_none;
    Dialog dialog;
    String content1="",content2="";
    EditText et_content1,et_content2;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hardwave_list);
        ButterKnife.bind(this);
        initIntent();
        initView();
//        initList();
initDialog();
        initLoad();

    }

    @Override
    protected Activity getContent() {
        return this;
    }

    @Override
    public void load() {
finish();
    }

    private void initIntent() {
        Bundle data = getIntent().getExtras();//获取数据包
//id=data.getString("id");
        msg = data != null ? data.getString("msg") : null;
        initToolBar(msg);
    }

    private void initView() {
        mPullToRefreshScrollView.setMode(PullToRefreshBase.Mode.BOTH);
        adapter = new ItemListAdapter(this);
        lv.setAdapter(adapter);
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                ItemListBean bean = adapter.getItem(i);

                switch (msg) {

                    case "固件信息":
                        Bundle bundle = new Bundle();
                        bundle.putString("id", bean.getID());
                        IntentUtils.startActivity(ChooseHardwaveListEmptyActivity.this, HardwaveInfActivity.class, bundle);

                        break;


                }


            }
        });
        customer(1, 1, "");

        mPullToRefreshScrollView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ScrollView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                //getHttp(1,1);
                page = 2;
                customer(1, 1, etSearch.getText().toString().trim());


            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                customer(page, 2, etSearch.getText().toString().trim());
                page += 1;


            }
        });
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                customer(1, 1, s.toString().trim());

            }
        });
    }

    private void initList() {
        String items[] = new String[]{"产线产量图", "产线OEE图", "产量推移图", "类型产量图"};
        for (int i = 0; i < items.length; i++) {
            ItemListBean bean = new ItemListBean(items[i], i + "");
            list.add(bean);
        }
        adapter.refreshData(list);
    }
    private void initDialog( ) {
        adapterItem=new ItemListAdapter(this);
        dialog = new Dialog(this, R.style.BottomDialog);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); // 设置Content前设定
        dialog.setContentView(R.layout.dialog_select_hard);
        dialog.setCanceledOnTouchOutside(true); // 外部点击取消
        // 设置宽度为屏宽, 靠近屏幕底部。
        final Window window = dialog.getWindow();
        window.setWindowAnimations(R.style.AnimBottom);
        final WindowManager.LayoutParams lp = window.getAttributes();
        lp.gravity = Gravity.BOTTOM; // 紧贴底部
        lp.width = WindowManager.LayoutParams.MATCH_PARENT; // 宽度持平
        lp.height = getWindowManager().getDefaultDisplay().getHeight() * 3 / 5;
        window.setAttributes(lp);

        rlIten1 = (RelativeLayout) dialog.findViewById(R.id.re_pay_way);
        rlItem2 = (RelativeLayout) dialog.findViewById(R.id.re_pay_way2);

        rlBase = (RelativeLayout) dialog.findViewById(R.id.re_pay_detail);//付款详情
        llItem = (LinearLayout) dialog.findViewById(R.id.lin_pay_way);//付款方式

        lvItem = (MyListView) dialog.findViewById(R.id.lv_bank);//付款方式（银行卡列表）
        lvItem.setAdapter(adapterItem);

        btnSearch = (Button) dialog.findViewById(R.id.btn_search);
        imageCloseOne= (ImageView) dialog.findViewById(R.id.close_one);
        imageCloseTwo= (ImageView) dialog.findViewById(R.id.close_two);
        iv_del1= (ImageView) dialog.findViewById(R.id.iv_del1);
        iv_del2= (ImageView) dialog.findViewById(R.id.iv_del2);

        iv_back= (ImageView) dialog.findViewById(R.id.iv_back);
        tv_content1= (TextView) dialog.findViewById(R.id.tv_content1);
        tv_content2= (TextView) dialog.findViewById(R.id.tv_content2);
        tv_none= (TextView) dialog.findViewById(R.id.tv_none);

        et_content1= (EditText) dialog.findViewById(R.id.et_content1);
        et_content2= (EditText) dialog.findViewById(R.id.et_content2);
        rlIten1.setOnClickListener(listener);
        rlItem2.setOnClickListener(listener);
        btnSearch.setOnClickListener(listener);
        imageCloseOne.setOnClickListener(listener);
        imageCloseTwo.setOnClickListener(listener);
        iv_back.setOnClickListener(listener);
        iv_del1.setOnClickListener(listener);
        iv_del2.setOnClickListener(listener);

        lvItem.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                ItemListBean bean = adapterItem.getItem(i);

                switch (type){
                    case 1:
                        tv_content1.setText(bean.getName());
                        content1=bean.getID();
                        iv_del1.setImageResource(R.mipmap.b_shut);
                        break;

                    case 2:
                        tv_content2.setText(bean.getName());
                        content2=bean.getID();
                        iv_del2.setImageResource(R.mipmap.b_shut);

                        break;
                }
                rlBase.startAnimation(slide_left_to_left_in);
                rlBase.setVisibility(View.VISIBLE);
                llItem.startAnimation(slide_left_to_right);
                llItem.setVisibility(View.GONE);
            }


        });


    }

    View.OnClickListener listener = new View.OnClickListener() {        @Override        public void onClick(View view) {            KeybordS.hideKeyboard(view);

            switch (view.getId()) {
                case R.id.re_pay_way://选择方式
                    type=1;
                    rlBase.startAnimation(slide_left_to_left);
                    rlBase.setVisibility(View.GONE);
                    llItem.startAnimation(slide_right_to_left);
                    llItem.setVisibility(View.VISIBLE);
                    break;
                case R.id.re_pay_way2://选择方式
                    initList();
                    type=2;
                    rlBase.startAnimation(slide_left_to_left);
                    rlBase.setVisibility(View.GONE);
                    llItem.startAnimation(slide_right_to_left);
                    llItem.setVisibility(View.VISIBLE);
                    break;

                case R.id.iv_back:
                    rlBase.startAnimation(slide_left_to_left_in);
                    rlBase.setVisibility(View.VISIBLE);
                    llItem.startAnimation(slide_left_to_right);
                    llItem.setVisibility(View.GONE);

                    break;
                case R.id.btn_search://确认付款
                    search();
                    break;
                case R.id.close_one:
                    dialog.dismiss();
                    break;
                case R.id.close_two:
                    dialog.dismiss();
                    break;
                case R.id.iv_del1:
                    content1="";
                    tv_content1.setText("请选择");
                    iv_del1.setImageResource(R.mipmap.right);
                    break;
                case R.id.iv_del2:
                    content2="";
                    tv_content2.setText("请选择");
                    iv_del2.setImageResource(R.mipmap.right);
                    break;
                default:
                    break;
            }
        }
    };

    public void search() {
        if (dialog!=null){
            dialog.dismiss();
        }

        OkHttpUtils
                .get(NewBaseUrl.hardwave_select)
                .params("token", token)
                .params("companyId", companyId)
                .params("hardwareCode",et_content1.getText().toString())
                .params("hardwareName",et_content2.getText().toString())

                .execute(new StringCallback() {

                    @Override
                    public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
                        super.onError(isFromCache, call, response, e);
                        PostUtil.postCallbackDelayed(loadService, ErrorCallback.class);
                    }

                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", "硬件查询列表: " + result);

                        list.clear();

                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");ViewUtil.lagout(code,getApplicationContext());
                        if (code == 0) {
                            JSONArray jsonArray = jsonObj.getJSONArray("hardwareInfoEntityList");
                            for (int i = 0; i < jsonArray.size(); i++) {
                                ItemListBean bean = new ItemListBean(jsonArray.getJSONObject(i).getString("hardwareName"), jsonArray.getJSONObject(i).getString("id"));
                                list.add(bean);
                            }
                            adapter.refreshData(list);
                            if (list.size() == 0) {
                                mMangeNodata.setVisibility(View.VISIBLE);
                            } else {
                                mMangeNodata.setVisibility(View.GONE);
                            }
                            adapter.notifyDataSetChanged();
                        } else {
                            ToastUtil.error(getApplicationContext(), jsonObj.getString("msg"));
                        }

                    }
                });
    }

    /*
      企业列表
   */
    public void customer(Integer page, final Integer type, String search) {


        OkHttpUtils
                .get(NewBaseUrl.hardware_list_get)
                .params("token", token)
                .params("key", search)
                .params("companyId", companyId)
                .params("limit", NewBaseUrl.num)                .params("page", page.toString())
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", "硬件列表: " + result);
                        if (type == 1) {
                            list.clear();
                        }
                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");ViewUtil.lagout(code,getApplicationContext());
                        if (code == 0) {
                            JSONObject Jpage = jsonObj.getJSONObject("page");
                            totalPage = Jpage.getIntValue("totalPage");
                            JSONArray jsonArray = Jpage.getJSONArray("list");
                            for (int i = 0; i < jsonArray.size(); i++) {
                                ItemListBean bean = new ItemListBean(jsonArray.getJSONObject(i).getString("hardwareName"), jsonArray.getJSONObject(i).getString("id"));
                                list.add(bean);
                            }
                            adapter.refreshData(list);
                            isEmpty(list,mMangeNodata);

                            adapter.notifyDataSetChanged();
                        } else {
                            ToastUtil.error(getApplicationContext(), jsonObj.getString("msg"));
                        }

                        mPullToRefreshScrollView.onRefreshComplete();
                    }
                });
    }

    @OnClick(R.id.tv_select)
    public void onViewClicked() {
        dialog.show();
    }

}

